<template>
  <div class="login-page">
    <div class="login-box">
      <div class="logo-box">
        <div class="right">
          <div class="sys-name">在线OJ</div>
          <div class="sys-sub-name">欲买桂花同载酒，终不似，少年游。</div>
        </div>
      </div>
      <div class="form-box">
        <div class="form-item" :class="{ 'focused': accountFocused }">
          <el-icon><User /></el-icon>
          <el-input
            v-model="mobileForm.email"
            placeholder="请输入邮箱"
            @focus="accountFocused = true"
            @blur="accountFocused = false"
            @keyup.enter="loginFun"
          />
        </div>
        <div class="form-item" :class="{ 'focused': passwordFocused }">
          <el-icon><Lock /></el-icon>
          <el-input
            v-model="mobileForm.code"
            type="text"
            placeholder="请输入验证码"
            @focus="passwordFocused = true"
            @blur="passwordFocused = false"
            @keyup.enter="loginFun"
          />
          <div class="code-btn-box" 
            @click="handleGetCode" 
            :class="{ 'loading': isLoading, 'disabled': isCountingDown }"
          >
            <span v-if="!isLoading && !isCountingDown">获取验证码</span>
            <span v-else-if="isCountingDown">{{ countdown }}秒后重试</span>
            <el-icon v-else class="is-loading"><Loading /></el-icon>
          </div>
        </div>
        <div class="submit-box" @click="loginFun" :class="{ 'loading': isLoading }">
          <span v-if="!isLoading">登录/注册</span>
          <el-icon v-else class="is-loading"><Loading /></el-icon>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'
import { User, Lock, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { sendCode, emailLogin } from '@/apis/user'
import { useRouter } from 'vue-router'
import { setToken } from '@/utils/cookie'

const router = useRouter()
const mobileForm = ref({
  email: '',
  code: ''
})
const isLoading = ref(false)
const accountFocused = ref(false)
const passwordFocused = ref(false)
const isCountingDown = ref(false)
const countdown = ref(60)
let countdownTimer = null

function startCountdown() {
  isCountingDown.value = true
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      isCountingDown.value = false
    }
  }, 1000)
}

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})

function isValidEmail(email) {
  const emailRegex = /^[\w-\.]+@[\w-\.]+\.[a-z]{2,4}$/i;
  return emailRegex.test(email);
}

async function handleGetCode() {
  if (!mobileForm.value.email) {
    ElMessage.warning('请输入邮箱');
    return;
  }

  if (!isValidEmail(mobileForm.value.email)) {
    ElMessage.error('邮箱格式不正确');
    return;
  }

  if (isLoading.value || isCountingDown.value) return;

  isLoading.value = true;
  try {
    const res = await sendCode(mobileForm.value.email);
    console.log('验证码发送结果：', {
      code: res.code,
      msg: res.msg,
      data: res.data
    });
    if (res.code === 1000) {
      ElMessage.success('操作成功');
      startCountdown();
    } else {
      ElMessage.error(res.msg || '验证码发送失败');
    }
  } catch (error) {
    console.error('验证码发送错误：', error);
    ElMessage.error(error.message || '获取验证码失败，请重试');
  } finally {
    isLoading.value = false;
  }
}

async function loginFun() {
  if (!mobileForm.value.email || !mobileForm.value.code) {
    ElMessage.warning('请输入邮箱和验证码');
    return;
  }

  if (!isValidEmail(mobileForm.value.email)) {
    ElMessage.error('邮箱格式不正确');
    return;
  }

  isLoading.value = true;
  try {
    const res = await emailLogin(mobileForm.value);
    console.log('登录结果：', res);
    
    if (res.code === 1000) {
      ElMessage.success('登录成功');
      // 保存token - 修改这里的逻辑
      if (res.data) {
        // 后端返回的token直接在data字段
        setToken(res.data);
        console.log('token已保存');
      }
      // 跳转到首页
      router.push('/c-oj/home/question');
    } else {
      ElMessage.error(res.msg || '登录失败');
    }
  } catch (error) {
    console.error('登录错误：', error);
    ElMessage.error(error.message || '登录失败，请重试');
  } finally {
    isLoading.value = false;
  }
}

function onSearch() {
  params.pageNum = 1
  getQuestionList()
}

const handleLogin = async () => {
  try {
    const response = await emailLogin({
      email: form.email,
      code: form.code
    });
    
    // 只处理登录成功的情况
    ElMessage.success('登录成功');
    // 其他登录成功后的逻辑...
    
  } catch (error) {
    // 不在这里处理错误，让全局拦截器来处理
    console.error('登录失败:', error);
  }
};
</script>

<style lang="scss" scoped>
@use 'sass:color';

.login-page {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  display: flex;
  justify-content: center;
  align-items: center;

  .login-box {
    width: 456px;
    background: #ffffff;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
    border-radius: 16px;
    padding: 48px 72px;
    animation: fadeIn 0.6s ease;
    transform: translateZ(0);
    backface-visibility: hidden;
    will-change: transform, opacity;

    @keyframes fadeIn {
      from {
        opacity: 0;
        transform: translateY(-24px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .logo-box {
      text-align: center;
      margin-bottom: 48px;

      .sys-name {
        font-size: 32px;
        font-weight: 600;
        color: #32C5FF;
        margin-bottom: 16px;
        letter-spacing: 2px;
        font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        text-shadow: 0 2px 4px rgba(50, 197, 255, 0.2);
      }

      .sys-sub-name {
        font-size: 16px;
        color: #606266;
        font-style: italic;
        font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      }
    }

    .form-box {
      .form-item {
        position: relative;
        margin-bottom: 24px;
        border-bottom: 2px solid #eee;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &.focused {
          border-color: #32C5FF;

          .el-icon {
            color: #32C5FF;
            transform: translateY(-50%) scale(1.1);
          }
        }

        .el-icon {
          font-size: 20px;
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          color: #909399;
        }

        :deep(.el-input__wrapper) {
          box-shadow: none !important;
          padding-left: 30px;
          background: transparent;

          &.is-focus {
            box-shadow: none !important;
          }

          .el-input__inner {
            height: 40px;
            font-size: 14px;
            color: #606266;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;

            &::placeholder {
              color: #909399;
              transition: opacity 0.3s;
            }

            &:focus::placeholder {
              opacity: 0.7;
            }
          }
        }

        .code-btn-box {
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
          color: #32C5FF;
          font-size: 14px;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          padding: 6px 10px;
          border-radius: 4px;
          user-select: none;

          &:hover {
            background-color: rgba(50, 197, 255, 0.1);
            transform: translateY(-50%) scale(1.02);
          }

          &:active {
            transform: translateY(-50%) scale(0.98);
          }

          &.loading, &.disabled {
            cursor: not-allowed;
            opacity: 0.6;
          }

          &.disabled:hover {
            background-color: transparent;
            transform: translateY(-50%);
          }
        }
      }

      .submit-box {
        margin-top: 48px;
        width: 100%;
        height: 48px;
        background: #32C5FF;
        border-radius: 8px;
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        font-size: 16px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        box-shadow: 0 4px 12px rgba(50, 197, 255, 0.3);
        user-select: none;

        &:hover {
          background: color.scale(#32C5FF, $lightness: -8.36%);
          transform: translateY(-2px);
          box-shadow: 0 6px 16px rgba(50, 197, 255, 0.4);
        }

        &:active {
          transform: translateY(0);
          box-shadow: 0 2px 8px rgba(50, 197, 255, 0.3);
        }

        &.loading {
          cursor: not-allowed;
          opacity: 0.8;
          transform: none;
          box-shadow: 0 4px 12px rgba(50, 197, 255, 0.2);
        }

        .is-loading {
          animation: rotating 2s linear infinite;
        }

        @keyframes rotating {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
      }
    }
  }
}

.el-message-box__content {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.el-message-box__status {
  font-size: 24px !important;
  margin-right: 12px !important;
  color: #E6A23C !important;
}

.el-message-box__message {
  padding-left: 0 !important;
}
</style>